#!/bin/bash

function __cas_prompt() {
    local cur prev opts base

    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD - 1]}"

    # Basic options
    opts="clean compile doxygen exec pip-download reconfigure run setup"

    if [[ ${COMP_CWORD} == 1 ]]; then
        # The first argument
        COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
        return 0
    fi

    # Complete the arguments to basic commands
    case "${COMP_WORDS[1]}" in
    clean | reconfigure | setup | doxygen | pip-download)
        COMPREPLY=() # not suggestion
        ;;
    compile)
        if [[ ${COMP_CWORD} -ge 2 ]]; then
            # TODO: erase options already typed
            COMPREPLY=($(compgen -W '-v --verbose -j --jobs --clean' -- "${cur}"))
        fi
        ;;
    run | exec)
        if [[ ${COMP_CWORD} == 2 ]]; then
            # only suggest for the second argument
            s1=$(find ./scratch/ -name '*.c*' | awk '{s=$1;sub(/^\.\//,"",s);sub(/\.c.*$/,"",s);print(s)}')
            s2=$(find ./examples/ -name '*.c*' | awk '{s=$1;sub(/^\.\//,"",s);sub(/\.c.*$/,"",s);print(s)}')
            COMPREPLY=($(compgen -W "${s1} ${s2}" -- ${cur}))
        fi
        ;;
    *)
        COMPREPLY=($(compgen -f ${cur}))
        ;;
    esac
    return 0
}

if [[ -n $1 ]]; then
    cd $1
fi

complete -F __cas_prompt ./cas
export -f __cas_prompt # export for detect its presence
